# -*- coding:utf-8 -*-
# @File    : apiMethod.py
# *************************
import os
import json
import random
import logging
import requests
import simplejson
from requests_toolbelt import MultipartEncoder
from comm.utils.readYaml import write_yaml_file, read_yaml_data
from config import ATMP_CONFIG,REPORT_DIR
import datetime,time
import uuid
import json
import os
from comm.utils import readYaml


config = readYaml.read_yaml_data(ATMP_CONFIG)
def atmpJson(config,url,data):
    headers = {"Content-Type": "application/json;charset=UTF-8", "User-Code": config["user_code"], "User-Pwd": config["user_pwd"]}
    response = requests.post(url=config["atmp_url"]+url, headers=headers, data=json.dumps(data))
    # response = requests.post(url=config["atmp_url"] + url, headers=headers, data=data)
    print("response:",response)
    print(response.request.url + " >> " + response.request.body)
    print(response.content.decode("utf8"))
    if response.status_code != 200:
        raise Exception("接口请求错误！")
    content = json.loads(response.content)
    return content


def atmpPost(config, url, data):
    headers = {"Content-Type": "application/x-www-form-urlencoded", "User-Code": config["user_code"], "User-Pwd": config["user_pwd"]}
    response = requests.post(url=config["atmp_url"] + url, headers=headers, data=data)
    print(response.request.url + " >> " + response.request.body)
    print(response.content.decode("utf8"))
    if response.status_code != 200:
        raise Exception("接口请求错误！")
    content = json.loads(response.content)
    time.sleep(1)
    return content


def addTask(config):
    """
    :param config:
    :return: 通过测试策略创建测试任务，生成测试任务id
    """
    post_data = {
        "schema_id": config["schema_id"],
        "tester": config["tester"]
    }
    response = atmpPost(config, "/edi/generate_task_schema", post_data)
    task_id = response["data"]["task_id"]
    return task_id


def reportData(self):
    reports = self.readJson()
    self.reportJson(reports)


def getTime(ts):
    t = datetime.datetime.fromtimestamp(ts)
    value = t.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
    return value


def getUnikey():
    value = uuid.uuid4()
    return str(value)


def getNowTime():
    value = datetime.datetime.now()
    return value


def getNowTimeStr():
    now = getNowTime()
    value = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
    return value


def addTaskLog(config, log_id, task_id, batch_no, test_code, run_plugin, fire_time, log_time, log_data, log_result, memo,sw=None):
    post_data = {
        "log_id": log_id,
        "task_id": task_id,
        "batch_no": batch_no,
        "group_code": config["group_code"],
        "test_code": test_code,
        "test_type": "function",
        "run_concurrent": 0,
        "run_cycle": 0,
        "tester": config["tester"],
        "run_plugin": run_plugin,
        "fire_time": fire_time,
        "log_time": log_time,
        "log_data": log_data,
        "log_result": log_result,
        "memo": memo
    }
    atmpJson(config, "/edi/add_task_log", post_data)


def reportCaseJson():
    jsonPath = REPORT_DIR + '\html\data\\test-cases\\'
    fileList = os.listdir(jsonPath)
    if config['task_id']:
        task_id = config['task_id']
    else:
        task_id = addTask(config)
    for file in fileList:
        p = jsonPath + '/' + file
        with open(p, encoding='utf-8') as f:
            c = f.read()
            f.close()
        d = json.loads(c)
        fire_time = getTime(int(d["time"]["start"]) / 1000.0)
        log_time = (d["time"]["stop"] - d["time"]["start"]) / 1000.0
        log_data = None
        success = d["status"]
        if success == "pass" or success == "passed":
            log_result = "pass_all"
            memo = "实际结果与预期一致"
        else:
            log_result = "fail"
            memo = d["statusMessage"]
        log_id = getUnikey()
        batch_no = getNowTimeStr()
        run_plugin = "bfftesting"
        caseName = d["name"]
        try:
            if caseName in str(config["tc_list"]):
                nameList = config["tc_list"][caseName]
            else:
                continue
        except:
            raise logging.error("atmpCaseConfig文件该用例名有问题：{}".format(caseName))
        # print("fire_time:",fire_time)
        # print("log_data:", log_data)
        # print("flog_time:", log_time)
        # print("log_id:", log_id)
        # print("batch_no:", batch_no)
        # print("run_plugin:", run_plugin)
        # print("caseName:", caseName)
        # print("log_result:", log_result)
        # print("memo:", memo)
        for name in nameList:
            test_code = name
            addTaskLog(config, log_id, task_id, batch_no, test_code, run_plugin, fire_time, log_time, log_data, log_result, memo)



